﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using MS.InformationManagement.Presenter.DeliveryMeans;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Support;
using System.Globalization;

namespace MS.InformationManagement.WP.DocumentCenter.DeliveryMeanConfig
{
    public partial class DeliveryMeanConfigUserControl : BaseControl, IDeliveryMeanConfigView
    {
        #region [Private Fields]

        private DeliveryMeanConfigPresenter _Presenter;

        #endregion

        #region [Event Handlers]

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Operation = "Add";
                _Presenter.HandleLoad();
                Pager1.BuildPager();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _Presenter = new DeliveryMeanConfigPresenter(this);
            Page.RegisterAjaxLoaderPlugin();
            btnAddConfig.AddLoader();
            btnSubmitOperation.AddLoader();
            
            
            txtbDeliveryMeanName.Required("El campo medio de envío es de caracter obligado", btnSubmitOperation.ValidationGroup, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);

            Pager1.OnPageChanged += new InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls.Pager.PageChangeHandler(OnPageChanged);
            //Pager1.NextLinkText = "Siguiente";
            //Pager1.PreviousLinkText = "Anterior";
            Pager1.NumberOfPagesToDisplay = 10;
            PageSize = 15;
            PageIndex = 0;
        }

        protected void OnPageChanged(object sender, Controls.PageChangeEventArgs e)
        {
            _Presenter.LoadDeliveryMeans();
            Pager1.BuildPager();
        }

        protected void btnSubmitOperation_Click(object sender, EventArgs e)
        {
            try
            {
                GatherDeliveryMeanConfigItems();
                if (!_Presenter.AreDeliveryConfigItemsValid()) {
                    HandleWarning("Verifique que los intervalos de peso para esta configuración se encuentren configurados correctamente");
                    return;
                }
                switch (Operation)
                {
                    case "Add":
                        if (_Presenter.CanAddDeliveryMean())
                        {
                            _Presenter.AddDeliveryMean();
                            HandleSuccess("El medio de envío ha sido agregado exitosamente.", null);
                        }
                        else
                        {
                            HandleWarning("No se puede agregar el medio de envío: ya existe otro medio de envio diferente con el nombre que se ha ingresado. Verifique e inténtelo de nuevo.");
                            return;
                        }
                        break;
                    case "Update":
                        if (_Presenter.CanUpdateDeliveryMean())
                        {
                            _Presenter.UpdateDeliveryMean();
                            HandleSuccess("El medio de envío ha sido actualizado exitosamente.", null);
                            Operation = "Add";
                        }
                        else
                        {
                            HandleWarning("No se puede actualizar el medio de envío: ya existe otro medio de envio diferente con el nombre que se ha ingresado. Verifique e inténtelo de nuevo.");
                            return;
                        }
                        break;
                }
                _Presenter.HandleLoad();
                Pager1.BuildPager();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnCancelOperation_Click(object sender, EventArgs e)
        {
            switch (Operation)
            {
                case "Add":
                    string isDlg = Request.QueryString.Get("IsDlg");
                    if (!string.IsNullOrEmpty(isDlg) && isDlg.Equals("1")) { this.CloseWindow(); }
                    else { this.GoCurrentUserHome(); }
                    break;
                case "Update":
                    Operation = "Add";
                    _Presenter.HandleLoad();
                    break;
            }
        }

        protected void btnDelete_DataBinding(object sender, EventArgs e)
        {
            ImageButton trigger = sender as ImageButton;
            trigger.OnClientClick = string.Format("return confirm('Esta seguro de que desea eliminar la {0}?')", trigger.OnClientClick);
        }

        protected void btnEdit_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                ImageButton trigger = sender as ImageButton;
                SelectedConfigId = Convert.ToInt32(trigger.CommandArgument);
                _Presenter.LoadDeliveryMean();
                Operation = "Update";
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnDelete_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                ImageButton trigger = sender as ImageButton;
                SelectedConfigId = Convert.ToInt32(trigger.CommandArgument);
                _Presenter.DeleteDeliveryMean();
                HandleSuccess("El medio de envío ha sido eliminado", null);
                _Presenter.HandleLoad();
                Pager1.BuildPager();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnAddConfig_Click(object sender, EventArgs e)
        {
            int index = rptConfigs.Items.Count - 1;
            RepeaterItem currentRow = rptConfigs.Items[index];

            TextBox txtbLocalCost = currentRow.FindControl("txtbLocalCost") as TextBox;
            TextBox txtbNationalCost = currentRow.FindControl("txtbNationalCost") as TextBox;
            TextBox txtbLowerLimit = currentRow.FindControl("txtbLowerLimit") as TextBox;
            TextBox txtbUpperLimit = currentRow.FindControl("txtbUpperLimit") as TextBox;

            System.Collections.Generic.List<DAL.DTOs.DeliveryMeanConfigDTO> configElements = DeliveryMeanConfigItems;
            DAL.DTOs.DeliveryMeanConfigDTO lastElement = configElements[index];
            lastElement.LocalCost = Convert.ToDouble(txtbLocalCost.Text);
            lastElement.NationalCost = Convert.ToDouble(txtbNationalCost.Text);
            lastElement.LowerWeightLimit = Convert.ToDouble(txtbLowerLimit.Text);
            lastElement.UpperWeightLimit = Convert.ToDouble(txtbUpperLimit.Text);


            configElements.Add(new DAL.DTOs.DeliveryMeanConfigDTO());
            DeliveryMeanConfigItems = configElements;

            //configElements[index].LocalCost = Convert.ToDouble(txtbLocalCost.Text);
            //configElements[index].NationalCost = Convert.ToDouble(txtbNationalCost.Text);
            //configElements[index].LowerWeightLimit = Convert.ToDouble(txtbLowerLimit.Text);
            //configElements[index].UpperWeightLimit = Convert.ToDouble(txtbUpperLimit.Text);
        }

        protected void rptConfigs_ItemCreated(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Separator)
            {
                TextBox txtbLocalCost = e.Item.FindControl("txtbLocalCost") as TextBox;
                TextBox txtbNationalCost = e.Item.FindControl("txtbNationalCost") as TextBox;
                TextBox txtbLowerLimit = e.Item.FindControl("txtbLowerLimit") as TextBox;
                TextBox txtbUpperLimit = e.Item.FindControl("txtbUpperLimit") as TextBox;

                txtbLocalCost.Required("Este campo es de caracter obligado", btnSubmitOperation.ValidationGroup, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
                txtbNationalCost.Required("Este campo es de caracter obligado", btnSubmitOperation.ValidationGroup, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
                txtbUpperLimit.Required("Este campo  es de caracter obligado", btnSubmitOperation.ValidationGroup, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
                txtbLowerLimit.Required("Este campo es de caracter obligado", btnSubmitOperation.ValidationGroup, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);

                txtbLocalCost.NumericWithSeparator();
                txtbNationalCost.NumericWithSeparator();
                txtbUpperLimit.NumericWithSeparator();
                txtbLowerLimit.NumericWithSeparator();
              
            }
        }

        #endregion

        #region [IDeliveryMeanConfigView Members]

        public int DeliveryMeanId
        {
            get { return ViewState["DeliveryMeanId"] == null ? 0 : Convert.ToInt32(ViewState["DeliveryMeanId"]); }
            set { ViewState["DeliveryMeanId"] = value; }
        }

        public int SelectedConfigId
        {
            get { return string.IsNullOrEmpty(btnSubmitOperation.CommandArgument) ? 0 : Convert.ToInt32(btnSubmitOperation.CommandArgument); }
            set { btnSubmitOperation.CommandArgument = value.ToString(); }
        }

        public int PageIndex
        {
            get { return Pager1.PageIndex; }
            set { Pager1.PageIndex = value; }
        }

        public int PageSize
        {
            get { return Pager1.PageSize; }
            set { Pager1.PageSize = value; }
        }

        public int TotalRecords
        {
            get { return Pager1.TotalRecords; }
            set
            {
                Pager1.TotalRecords = value;
            }
        }

        public string DeliveryMeanTitle
        {
            get
            {
                return txtbDeliveryMeanName.Text;
            }
            set
            {
                txtbDeliveryMeanName.Text = value;
            }
        }

        public bool IsSecureDeliveryMean {
            get { return chkIsSecureDelivery.Checked; }
            set { chkIsSecureDelivery.Checked = value; } 
        }

        public System.Collections.Generic.List<DAL.DocumentCenter.ConfiguracionDeCostosDeMedioDeEnvio> DeliveryMeans
        {
            get
            {
                return grdDeliveryMeans.DataSource as System.Collections.Generic.List<DAL.DocumentCenter.ConfiguracionDeCostosDeMedioDeEnvio>;
            }
            set
            {
                grdDeliveryMeans.DataSource = value;
                DataBind();
            }
        }

        public System.Collections.Generic.List<DAL.DTOs.DeliveryMeanConfigDTO> DeliveryMeanConfigItems
        {
            get
            {
                return ViewState["DeliveryMeanConfigItems"] as System.Collections.Generic.List<DAL.DTOs.DeliveryMeanConfigDTO>;
            }
            set
            {
                ViewState["DeliveryMeanConfigItems"] = value;
                rptConfigs.DataSource = value;
                rptConfigs.DataBind();
            }
        }

        public string Operation
        {
            get { return btnSubmitOperation.CommandName; }
            set
            {
                btnSubmitOperation.CommandName = value;
                switch (value)
                {
                    case "Add":
                        btnSubmitOperation.Text = "Guardar";
                        h3Title.InnerText = "Nuevo Medio de Envío";
                        break;
                    case "Update":
                        btnSubmitOperation.Text = "Actualizar";
                        h3Title.InnerText = "Actualizar Medio de Envío";
                        break;
                }
            }
        }

        #endregion

        #region [Private Members]

        private void GatherDeliveryMeanConfigItems()
        {
            System.Collections.Generic.List<DAL.DTOs.DeliveryMeanConfigDTO> configItems = DeliveryMeanConfigItems;
            RepeaterItemCollection uiConfigItems = rptConfigs.Items;
            for (int index = 0; index < configItems.Count; index++)
            {
                RepeaterItem currentUIItem = uiConfigItems[index];

                TextBox txtbLocalCost = currentUIItem.FindControl("txtbLocalCost") as TextBox;
                TextBox txtbNationalCost = currentUIItem.FindControl("txtbNationalCost") as TextBox;
                TextBox txtbLowerLimit = currentUIItem.FindControl("txtbLowerLimit") as TextBox;
                TextBox txtbUpperLimit = currentUIItem.FindControl("txtbUpperLimit") as TextBox;
                HiddenField hdfID = currentUIItem.FindControl("hdfID") as HiddenField;

                DAL.DTOs.DeliveryMeanConfigDTO currentItem = configItems[index];
                currentItem.LocalCost = Convert.ToDouble(txtbLocalCost.Text, CultureInfo.CurrentCulture.NumberFormat);
                currentItem.NationalCost = Convert.ToDouble(txtbNationalCost.Text, CultureInfo.CurrentCulture.NumberFormat);
                currentItem.LowerWeightLimit = Convert.ToDouble(txtbLowerLimit.Text, CultureInfo.CurrentCulture.NumberFormat);
                currentItem.UpperWeightLimit = Convert.ToDouble(txtbUpperLimit.Text, CultureInfo.CurrentCulture.NumberFormat);
                currentItem.Id = Convert.ToInt32(hdfID.Value);
            }

        }

       #endregion
    }
}
